// @Date         2021-11-25
// @Author       Aaron Zhang
// @Description   创建命令工具
// @FileName      command.go

package command

import (
	"errors"
	"fmt"
	"github.com/scylladb/termtables"
	"os"
	"path/filepath"
	"zin/framework/cobra"
	"zin/framework/command/template"
	"zin/framework/util"
)

func initCommandCommand() *cobra.Command {
	parseCommandFlag()
	commandCommand.AddCommand(newCommandCommand, commandListCommand)
	return commandCommand
}

var commandCommand = &cobra.Command{
	Use:   "command",
	Short: "创建一个命令工具",
	RunE: func(cmd *cobra.Command, args []string) error {
		cmd.Help()
		return nil
	},
}

var commandListCommand = &cobra.Command{
	Use:   "list",
	Short: "查看系统包含哪些命令",
	RunE: func(cmd *cobra.Command, args []string) error {
		commands := cmd.Root().Commands()
		t := termtables.CreateTable()
		t.AddHeaders("command", "Short")
		for _, v := range commands {
			t.AddRow(v.Use, v.Short)
		}
		res := t.Render()
		fmt.Println(res)
		return nil
	},
}

var newCommandCommand = &cobra.Command{
	Use:   "new",
	Short: "创建一个命令",
	RunE: func(cmd *cobra.Command, args []string) error {
		if commandName == "" {
			return errors.New("命令的名称不能为空")
		}

		commandFolder := util.GetAppProvider().CommandFolder()
		fInfo, _ := os.Stat(filepath.Join(commandFolder, commandName, commandName+".go"))
		if fInfo != nil {
			return errors.New("命令文件已经存在")
		}

		err := template.CreateNewCommand(commandName)
		if err != nil {
			return err
		}

		fmt.Println("命令创建成功", filepath.Join(commandFolder,commandName,commandName+".go"))

		return nil
	},
}

//解析 new 后面的 flag参数，控制是否后台运行
var commandName string // command name
func parseCommandFlag() {
	newCommandCommand.Flags().StringVarP(&commandName, "name", "n", "", "命令名称")
}
